<template>
  <div>
    <n-button size="medium" @click="clear(), (changePassword = true)">修改登录密码</n-button>
    <n-modal
      v-model:show="changePassword"
      :mask-closable="false"
      preset="dialog"
      title="修改登录密码"
    >
      <n-form :model="model" ref="formRef" :rules="rules">
        <n-form-item path="password" label="当前登录密码">
          <n-input
            v-model:value="model.password"
            @keydown.enter.prevent
            :show-button="false"
            style="width: 100%"
            maxlength="30"
          />
        </n-form-item>
        <n-form-item path="newPassword" label="新密码" style="margin-top: 10px">
          <n-input
            v-model:value="model.newPassword"
            @input="handlePasswordInput"
            type="password"
            @keydown.enter.prevent
            style="width: 100%"
            maxlength="30"
          />
        </n-form-item>
        <n-space justify="right">
          <n-form-item>
            <n-space>
              <n-button @click="changePassword = false" size="medium">取消</n-button>
              <n-button @click="updateConfirm" attr-type="button" size="medium" type="info"
                >确认</n-button
              >
            </n-space>
          </n-form-item>
        </n-space>
      </n-form>
    </n-modal>
  </div>
</template>

<script lang='ts' setup>
import { updatePassword } from '@/api/merchantPassword/updatePassword';
import { ref } from 'vue';
import { useMessage } from 'naive-ui';
import { createStorage } from '@/utils/Storage';
import { useRouter } from 'vue-router';
import md5 from 'js-md5';

const router = useRouter();
const Storage = createStorage({ storage: localStorage });

const changePassword = ref(false); // 是否显示模态框

const formRef = ref(null);

const rPasswordFormItemRef = ref(null); // 确认密码框值

const message = useMessage();

let userIdValue = ref(Storage.get('userId'));
console.log(userIdValue.value);

const modelRef = ref({
  password: null,
  newPassword: null,
  userId: userIdValue.value,
});

function validatePasswordSame(rule, value) {
  return value === modelRef.value.newPassword;
}

// 判断第二次密码与第一次是否一样（失去焦点判断）
const model = modelRef;

// const password = ref('f0KuY6Fq'); // 原密码的值（做对比使用）

// 表单验证规则
const rules = {
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入密码');
        } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,12}$/.test(value)) {
          return new Error('密码为8-12位并且由数字和字母大小写组成');
        } else {
          return true;
        }
      },
      trigger: 'blur',
    },
  ],
};

// 修改登录密码
const updateConfirm = async (e) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      console.log(modelRef.value);
      modelRef.value.password = md5(modelRef.value.password)
      modelRef.value.newPassword = md5(modelRef.value.newPassword)
      await updatePassword(modelRef.value).then((res) => {
        console.log(res);
        if (res.data.sysHead.retCd == '000000') {
          message.success('修改登录密码成功');
          clear();
          changePassword.value = false;
          router.push('/login');
        } else {
          message.success('修改登录密码失败');
          clear();
        }
      });
    } else {
      message.error('请按照提示正确填写需要修改的密码');
    }
  });
};

// 点击叉号关闭 清空输入框值
const clear = () => {
  model.value.password = null;
  model.value.newPassword = null;
};
</script>